//
//  KATTableFooter.m
//  KATFramework
//
//  Created by Kantice on 16/7/19.
//  Copyright © 2016年 KatApp. All rights reserved.
//

#import "KATTableFooter.h"

@implementation KATTableFooter


#pragma -mark 类方法

//获取实例
+ (instancetype)tableFooter
{
    return [[[KATTableFooter alloc] init] autorelease];
}


#pragma -mark 对象方法

//初始化数据
- (void)initWithHeight:(float)height andScrollView:(UIScrollView *)scrollView
{
    if(scrollView)
    {
        if(height<=0)
        {
            height=scrollView.bounds.size.width*0.2;
        }
        
        self.scrollView=scrollView;
        self.bounds=CGRectMake(0, 0, scrollView.bounds.size.width, height);
        self.dragHeight=height*1.5;
        self.state=TFOOTER_STATE_READY;
        self.isReleaseToLoad=NO;
        self.animationFinishDuration=0.8;
        self.eventDelegate=nil;
        self.locked=NO;
        self.ignoreConflicts=YES;
        _disabled=NO;
        
        [self updatePosition];
        
        //内容尺寸监听
        [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
        [self.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
        
        _footerQueue=dispatch_queue_create("kat_table_footer_queue", DISPATCH_QUEUE_SERIAL);
    }
}


//更新位置
- (void)updatePosition
{
    if(_scrollView)
    {
        [self removeFromSuperview];
        
        self.frame=CGRectMake(0, (_scrollView.bounds.size.height>=_scrollView.contentSize.height?_scrollView.bounds.size.height:_scrollView.contentSize.height), _scrollView.bounds.size.width, self.bounds.size.height);
        
        [_scrollView addSubview:self];
    }
}


//禁用(不显示)
- (void)disableFooter
{
    if(!_disabled)
    {
        _disabled=YES;
        
        self.scrollView.contentInset=UIEdgeInsetsMake(0, 0, 0, 0);
        
        self.hidden=YES;
    }
}


//启用(显示)
- (void)enableFooter
{
    if(_disabled)
    {
        _disabled=NO;
        
        [self updatePosition];
        
        self.hidden=NO;
    }
}


//上推
- (void)push
{
    if(_stateDelegate && [_stateDelegate respondsToSelector:@selector(footerPushWithProgress:)])
    {
        float compareHeight=(_scrollView.contentSize.height<=_scrollView.bounds.size.height?0:(_scrollView.contentSize.height-_scrollView.bounds.size.height));//对比的高度
        
        float progress=(_scrollView.contentOffset.y-compareHeight)/_dragHeight;
        
        if(progress<0)
        {
            progress=0;
        }
        
        if(progress>1.0)
        {
            progress=1.0;
        }
        
        [_stateDelegate footerPushWithProgress:progress];
    }
    
    _state=TFOOTER_STATE_PUSHING;
}


//直接加载
- (void)load
{
    if(_eventDelegate && [_eventDelegate respondsToSelector:@selector(tableFooterDidStartLoad:)])
    {
        [_eventDelegate tableFooterDidStartLoad:self];
    }
}


//开始加载
- (void)startLoad
{
    if(!_ignoreConflicts)//冲突判断
    {
        if(self.scrollView.contentInset.top>0)//正在加载中
        {
            return;
        }
    }
    
    _state=TFOOTER_STATE_LOADING;
    
    dispatch_async(_footerQueue, ^
    {
        dispatch_sync(dispatch_get_main_queue(), ^
        {
            if(_stateDelegate && [_stateDelegate respondsToSelector:@selector(footerStartLoad)])
            {
                [_stateDelegate footerStartLoad];
            }
        });
        
        [NSThread sleepForTimeInterval:0.8];//防止冲突，先挂起一会
        
        dispatch_sync(dispatch_get_main_queue(), ^
        {
            if(_eventDelegate && [_eventDelegate respondsToSelector:@selector(tableFooterDidStartLoad:)])
            {
                [_eventDelegate tableFooterDidStartLoad:self];
            }
        });
    });
    
}


//完成加载
- (void)finishLoad
{
    _state=TFOOTER_STATE_FINISH;
    _scrollView.userInteractionEnabled=NO;
    
    if(_stateDelegate && [_stateDelegate respondsToSelector:@selector(footerFinishLoad)])
    {
        [_stateDelegate footerFinishLoad];
    }
    
    self.scrollView.contentInset=UIEdgeInsetsMake(0, 0, 0, 0);
    
    if(_stateDelegate && [_stateDelegate respondsToSelector:@selector(footerRestoreAfterLoad)])
    {
        [_stateDelegate footerRestoreAfterLoad];
    }
    
    [self updatePosition];
    
    _scrollView.userInteractionEnabled=YES;
    _state=TFOOTER_STATE_READY;
    
}


//监听状态
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if(_scrollView && !_disabled)
    {
        if([@"contentOffset" isEqualToString:keyPath])
        {
            float compareHeight=(_scrollView.contentSize.height<=_scrollView.bounds.size.height?0:(_scrollView.contentSize.height-_scrollView.bounds.size.height));//对比的高度
            
            if(_scrollView.contentOffset.y-compareHeight>0)
            {
                if(_scrollView.contentOffset.y-compareHeight>=_dragHeight)//上推完成
                {
                    if(_state==TFOOTER_STATE_PUSHING)
                    {
                        if(_stateDelegate && [_stateDelegate respondsToSelector:@selector(footerFinishPush)])
                        {
                            [_stateDelegate footerFinishPush];
                        }
                        
                        _state=TFOOTER_STATE_RELEASE;
                    }
                    
                    if(_state==TFOOTER_STATE_RELEASE)//下拉完成状态
                    {
                        if(_isReleaseToLoad)//需要松开后
                        {
                            if(_scrollView.decelerating)//减速中(松开后)
                            {
                                if(!_locked)
                                {
                                    [self startLoad];
                                }
                            }
                        }
                        else//不需要松开，直接加载
                        {
                            if(!_locked)
                            {
                                [self startLoad];
                            }
                        }
                    }
                }
                else
                {
                    if(_state==TFOOTER_STATE_LOADING)
                    {
                        if(_scrollView.decelerating)
                        {
                            if(self.scrollView.contentInset.bottom<=0)
                            {
                                [UIView animateWithDuration:0.1 animations:^
                                {
                                    self.scrollView.contentInset=UIEdgeInsetsMake(0, 0, (_scrollView.contentSize.height<_scrollView.bounds.size.height?(_scrollView.bounds.size.height-_scrollView.contentSize.height+self.bounds.size.height):self.bounds.size.height), 0);
                                }
                                completion:^(BOOL finished)
                                {
                                    ;
                                }];
                            }
                        }
                    }
                    else if(_state==TFOOTER_STATE_FINISH)
                    {
                        
                    }
                    else
                    {
                        [self push];
                    }
                }
            }
            else
            {
                if(_state!=TFOOTER_STATE_LOADING && _state!=TFOOTER_STATE_FINISH)
                {
                    _state=TFOOTER_STATE_READY;
                    
                    if(_scrollView.contentInset.bottom>0)
                    {
                        self.scrollView.contentInset=UIEdgeInsetsMake(0, 0, 0, 0);
                    }
                }
            }
        }
        else if([@"contentSize" isEqualToString:keyPath])
        {
            [self updatePosition];
        }
    }
}


//释放内存
- (void)dealloc
{
    if(_scrollView)
    {
        @try
        {
            [_scrollView removeObserver:self forKeyPath:@"contentSize"];//移除监听
            [_scrollView removeObserver:self forKeyPath:@"contentOffset"];//移除监听
        }
        @catch(NSException *exception)
        {
            NSLog(@"<Exception> %@ : %@",self,exception);
        }  
    }
    
    if(_footerQueue)
    {
        dispatch_release(_footerQueue);
    }
    
    [super dealloc];
}


@end
